package com.jp.knowledge.comm;

import android.app.Activity;
import android.app.Service;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;

import com.dmcc.image_preview.ImagePreviewActivity;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.internal.Supplier;
import com.facebook.common.util.ByteConstants;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.decoder.SimpleProgressiveJpegConfig;
import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.jp.knowledge.dialog.FirstLoginDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.Constant;
import com.jp.knowledge.util.PushUtil;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.view.JpApplicationWebView;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiayen on 16/9/28.
 */
public class JpApplication extends MultiDexApplication {

    public final static  String   weixin_appid="wx73bea73b9ead58e8";
    public final static String weixin_key="a97fb5d166240fbe0e8270aa344835f8";
    private UserData userData;
    public static boolean IS_LOGIN=false;
    public List<Activity> loginActivitys = new ArrayList<>();
    public List<Activity> activities = new ArrayList<>();
    public List<Service> services = new ArrayList<>();

    {
        PlatformConfig.setWeixin("wx73bea73b9ead58e8", "9db2a5dda3f0ca977859cc9ad414a0b8");//微信
        PlatformConfig.setSinaWeibo("4266495195", "d4b40e7a050dd575c9f58a4f41754abd");//微博
        PlatformConfig.setQQZone("1105742700", "o3gApiarb9NGcYNl");//QQ
    }

    public static String token = "";
    public static String uuid = "";

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init(){
        UMShareAPI.get(this);
        initXutils();
        initFrescoConfig();
        initPushSdk();
        initIFly();
        registerActivityLifecycleCallbacks(ParallaxHelper.getInstance());
//        initApplicationWebView();
//        JpCrashHandler.getInstance().init(this);//初始化异常捕获
//        MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);//友盟统计
    }

    private JpApplicationWebView applicationWebView;
    private void initApplicationWebView(){
        this.applicationWebView = JpApplicationWebView.getInstance(this);
    }
    public JpApplicationWebView getApplicationWebView(){
        if(applicationWebView == null)
            this.applicationWebView = JpApplicationWebView.getInstance(this);
        return this.applicationWebView;
    }

    /**
     * 初始化友盟推送SDK
     */
    private void initPushSdk(){
        PushUtil.getInstance(this);
    }

    /* 初始化讯飞 */
    private void initIFly(){
        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=58c811e3");
    }

    /**
     * 初始化xutils
     */
    private void initXutils() {
        x.Ext.init(this);
        x.Ext.setDebug(Constant.isDebug); // 开启debug会影响性能
//        UMShareAPI.get(this);
    }


    /**
     * 添加登录接口
     *
     * @param activity
     */
    public void putLoginActivity(Activity activity) {
        loginActivitys.add(activity);
    }


    public void addActivity(Activity activity){
        activities.add(activity);
    }
    /**
     * 关闭登录接口
     */
    public void closeLoginActivity() {
        for (Activity activity : loginActivitys)
            activity.finish();
        loginActivitys.clear();
    }


    public void finish() {
        for (Activity activity : activities)
            activity.finish();
        for (Service service:services)
            service.stopSelf();
//        System.exit(0);
    }

    public UserData getUserData() {
        return userData;
    }

    public void setUserData(UserData userData) {
        this.userData = userData;
    }


    public void addService(Service service){
        services.add(service);
    }
    /**
     * 判断登录状态
     * @return
     */
    public boolean isLogin(){
        if(userData==null)return false;
        if(userData.getIsLogin()==0)return false;
        return  true;
    }

    public void clearLoginInfo(){
        userData=null;
        SharedUtil.getInstance(getApplicationContext()).cleanLoginInfo();
        HttpHelper.token=null;
        HttpHelper.uuid=null;
    }


    // 初始化 Fresco
    private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();
    public static final int MAX_DISK_CACHE_SIZE = 50 * ByteConstants.MB;
    public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 8;

    private void initFrescoConfig() {
        final MemoryCacheParams bitmapCacheParams =
                new MemoryCacheParams(MAX_MEMORY_CACHE_SIZE, // Max total size of elements in the cache
                        Integer.MAX_VALUE,                     // Max entries in the cache
                        MAX_MEMORY_CACHE_SIZE, // Max total size of elements in eviction queue
                        Integer.MAX_VALUE,                     // Max length of eviction queue
                        Integer.MAX_VALUE);
        ImagePipelineConfig config = OkHttpImagePipelineConfigFactory.newBuilder(this, ImagePreviewActivity.getOkHttpClient())
                .setProgressiveJpegConfig(new SimpleProgressiveJpegConfig())
                .setBitmapMemoryCacheParamsSupplier(new Supplier<MemoryCacheParams>() {
                    public MemoryCacheParams get() {
                        return bitmapCacheParams;
                    }
                })
                .setMainDiskCacheConfig(
                        DiskCacheConfig.newBuilder(this).setMaxCacheSize(MAX_DISK_CACHE_SIZE).build())
                .setDownsampleEnabled(true)
                .build();
        Fresco.initialize(this, config);
    }

    /**
     * 用于短信验证
     * */
    private int nextSendMsgTime = 0;
    private Handler sendMsgHandler = new Handler();
    private Runnable sendMsgRunnable = new Runnable() {
        @Override
        public void run() {
            if(--nextSendMsgTime > 0){
                if(sendMsgRunnable != null)
                    sendMsgHandler.postDelayed(sendMsgRunnable, 1000);
            } else{
                if(nextSendMsgTime < 0)
                    nextSendMsgTime = 0;
            }
            if(timerCallBack != null)
                timerCallBack.timerCallBack(nextSendMsgTime);
        }
    };
    public int getNextSendMsgTime(){
        return nextSendMsgTime;
    }

    public void setNextSendMsgTime(int nextSendMsgTime){
        this.nextSendMsgTime = nextSendMsgTime;
    }
    public void startTimerCountdown(){
        sendMsgHandler.removeCallbacks(sendMsgRunnable);
        sendMsgHandler.postDelayed(sendMsgRunnable, 1000);
    }
    public interface SendMsgTimerCallBack {
        void timerCallBack(int time);
    }
    private SendMsgTimerCallBack timerCallBack;
    public void setTimerCallBack(SendMsgTimerCallBack callBack){
        timerCallBack = callBack;
    }
}
